package ld.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
public class MybatisUtil {


	/**
	 * 1. 获取SqlSessionFactory
	 * @return
	 * @throws IOException
	 */
	private static SqlSessionFactory getSqlSessionFactory() throws IOException {
		String resource = "config/mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		return sqlSessionFactory;
	}

	/**
	 * 2. 得到sqlSession对象
	 * @return
	 */
	public static SqlSession getSqlSession(){
		SqlSessionFactory sqlSessionFactory = null;
		try {
			sqlSessionFactory = getSqlSessionFactory();
			return sqlSessionFactory.openSession(true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void closeSession(SqlSession session){
		if (session != null) {
			session.close();
		}
	}
}
